import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: RefreshLoadMorePage()
    );
  }
}

class RefreshLoadMorePage extends StatefulWidget {
  @override
  _RefreshLoadMorePageState createState() => _RefreshLoadMorePageState();
}

class _RefreshLoadMorePageState extends State<RefreshLoadMorePage> {
  // Define variables
  List<String> items = [];
  bool isLoading = false;
  ScrollController scrollController = ScrollController();

  // Define function to load more items
  void loadMoreItems() async {
    setState(() {
      isLoading = true;
    });
    // Simulate loading more items
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      isLoading = false;
      items.addAll(List.generate(20, (index) => 'Item ${items.length + index + 1}'));
    });
  }

  // Define function to refresh items
  Future<void> refreshItems() async {
    // Simulate refreshing items
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      items = List.generate(10, (index) => 'Item ${index + 1}');
    });
  }

  @override
  void initState() {
    super.initState();
    // Initialize the list with some items
    items = List.generate(20, (index) => 'Item ${index + 1}');
    // Add listener to the scroll controller
    scrollController.addListener(() {
      if (scrollController.position.pixels == scrollController.position.maxScrollExtent) {
        loadMoreItems();
      }
      if (scrollController.position.pixels == scrollController.position.minScrollExtent) {
        debugPrint('you got top');
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    // Dispose of the scroll controller
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Refresh and Load More'),
      ),
      body: RefreshIndicator(
        onRefresh: refreshItems,
        child: ListView.builder(
          controller: scrollController,
          itemCount: items.length + 1,
          itemBuilder: (BuildContext context, int index) {
            if (index == items.length) {
              return Center(
                child: isLoading ? CircularProgressIndicator() : SizedBox(),
              );
            } else {
              return ListTile(
                title: Text(items[index]),
              );
            }
          },
        ),
      ),
    );
  }
}

